#!/bin/bash
# Desc: xRDP一键安装脚本（支持Ubuntu 18.04+/CentOS 7+）
# Author: AI助手（基于CSDN/博客园等技术文档编写）
# Date: 2025-04-08

# 检测root权限
if [ "$(id -u)" != "0" ]; then
   echo "错误：必须使用root权限运行此脚本！" 
   exit 1
fi

# 定义变量
XRDP_PORT=3389
DESKTOP_ENV="gnome"  # 可选gnome/xfce

# 函数：安装Ubuntu/Debian环境
install_ubuntu() {
    echo "开始更新系统及安装依赖..."
    apt update -y
    apt upgrade -y
    apt install -y xrdp tigervnc-standalone-server $DESKTOP_ENOME-core

    # 配置xrdp会话环境（解决黑屏问题）[5](@ref)
    sed -i '/test -x \/etc\/X11/i\gnome-session' /etc/xrdp/startwm.sh

    # 修改默认端口（可选）[2](@ref)
    sed -i "s/port=3389/port=$XRDP_PORT/g" /etc/xrdp/xrdp.ini

    ufw allow $XRDP_PORT/tcp
    ufw reload
}

install_centos() {
    echo "安装EPEL仓库及依赖..."
    yum install -y epel-release
    yum groupinstall -y "X Window System" "GNOME Desktop"
    yum install -y xrdp tigervnc-server

    sed -i 's/SELINUX=enforcing/SELINUX=permissive/g' /etc/selinux/config
    setenforce 0

    echo "请为当前用户设置VNC密码："
    vncpasswd

    firewall-cmd --permanent --add-port=$XRDP_PORT/tcp
    firewall-cmd --reload
}

if grep -qEi "debian|ubuntu" /etc/os-release; then
    install_ubuntu
elif grep -qEi "centos|redhat" /etc/os-release; then
    install_centos
else
    echo "错误：不支持此操作系统！"
    exit 1
fi

echo "优化xrdp参数..."
sed -i 's/max_bpp=32/max_bpp=24/g' /etc/xrdp/xrdp.ini  # 改善显示性能[1](@ref)
systemctl restart xrdp
systemctl enable xrdp

echo "安装完成！验证服务状态："
systemctl status xrdp | grep "Active:"
ss -tuln | grep $XRDP_PORT

echo -e "\n连接信息："
echo "IP地址：$(hostname -I | awk '{print $1}')"
echo "端口：$XRDP_PORT"
echo "协议：RDP (使用Windows远程桌面工具连接)"